import logging
from event_rule import rule_config
from event_rule.const import ValueType, EventFormatError

_LOGGER = logging.getLogger(__name__)


def transform_event(event, tenant_name):
    """
    验证并转换数据
    :param event: 日志数
    :param tenant_name: 商户代号
    :return:
    """
    if '_id' not in event\
            or '_event_id' not in event\
            or '_event_time' not in event:
        raise EventFormatError('event must contains [_id] [_event_id] [_event_time]')

    data = dict(_event_id=str(event['_event_id']), _event_time=event['_event_time'])
    data['_id'] = str(event['_id'])
    if tenant_name not in rule_config.RULE_CONFIG:
        raise KeyError('tenant not config: {}'.format(tenant_name))
    event_rule = rule_config.RULE_CONFIG[tenant_name]
    event_id = event['_event_id']
    if event_id not in event_rule:
        raise KeyError('the tenant: {} has no event config: {}'.format(tenant_name, event_id))
    for field_id, field_rule in event_rule[event_id].get("values", {}).items():
        if field_rule.get('required', True):
            if field_id not in event:
                raise KeyError(
                    'the field: {} missed of the tenant: {}, the event id: {}'.format(field_id, tenant_name, event_id))
        value_type = ValueType(field_rule['value_type'].lower()) if 'value_type' in field_rule else ValueType.LONG
        if field_id in event:
            if field_rule.get('allow_null', False) and event[field_id] is None:
                continue
            else:
                data[field_id] = _convert_data_by_type(event[field_id], value_type)
    return data


def _convert_data_by_type(value, value_type):
    assert isinstance(value_type, ValueType)
    if value_type == ValueType.LONG:
        value = int(value)
    elif value_type == ValueType.FLOAT:
        value = float(value)
    elif value_type == ValueType.STRING:
        value = str(value)
    return value
